package file

import (
	"bufio"
	"bytes"
	"io"
	"os"
)

func ReadLines(path string) ([]string, error) {
	lines := []string{}
	if err := LoadLines(path, func(line []byte) error {
		lines = append(lines, string(line))
		return nil
	}); err != nil {
		return nil, err
	}
	return lines, nil
}

func LoadLines(path string, walk func([]byte) error) error {
	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	var buffer bytes.Buffer

	for {
		part, prefix, err := reader.ReadLine()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}
		buffer.Write(part)
		if !prefix {
			b := buffer.Bytes()
			line := make([]byte, len(b))
			copy(line, b)
			buffer.Reset()
			if err := walk(line); err != nil {
				return err
			}
		}
	}
	return nil
}
func LoadLinesForReader(file io.Reader, walk func(string) error) error {
	br := bufio.NewReader(file)
	for {
		s, _, c := br.ReadLine()
		if c == io.EOF {
			break
		}
		err := walk(string(s))
		if err != nil {
			return err
		}
	}
	return nil
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
